package pw.hais.braintwists.dao;

import com.squareup.okhttp.Response;

import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import pw.hais.braintwists.enums.ArticleType;
import pw.hais.braintwists.model.Article;
import pw.hais.http.Http;
import pw.hais.http.base.OnHttpListener;

/**
 * Created by Hais1992 on 2015/12/11.
 */
public class Tools2345Dao {

    public static void getBrainTwists(ArticleType type, int page, final OnHttpListener<List<Article>> listener) {
        String url = "http://tools.2345.com/jzw/ajaxList.php";
        Map<String, String> data = new HashMap<>();
        data.put("page", page + "");
        data.put("type", type.type + "");
        Http.get(url, data, new OnHttpListener<JSONObject>() {
            @Override
            public void onSuccess(Response response, JSONObject data) {
                String html = data.optString("list");
                doHtmlToModel(html, listener);
            }
        });
    }

    private static void doHtmlToModel(String html, OnHttpListener<List<Article>> listener) {
        Document document = Jsoup.parse(html);
        Elements elements = document.getElementsByAttribute("onmouseout");
        List<Article> list = new ArrayList<>();
        for (Element e : elements) {
            String problem = e.select("p").text();
            String answer = e.getElementsByClass("brain_aw").select("a").attr("onclick").replace("pop_show(event, '", "").replace("');", "");
            list.add(new Article(problem, answer));
        }
        listener.onSuccess(null, list);
    }
}
